#pragma once
#include<iostream>
using namespace std;

// 枚举值表示颜色
enum  Color
{
	RED,
	BLACK
};

// T存储实际存储的数据类型
template<class T>
struct RBTreeNode
{
	// 这里更新控制平衡也要加入parent指针
	T _kv;
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	Color _col;

	RBTreeNode(const T& kv)
		:_kv(kv),
		_left(nullptr),
		_right(nullptr),
		_parent(nullptr),
		_col(RED)
	{
	}
};

template<class T, class Ref, class Ptr>
struct RBTreeIterator
{
	typedef RBTreeNode<T> Node;
	typedef RBTreeIterator<T, Ref, Ptr> Self;
	RBTreeIterator(Node* node, Node* root)
		:_node(node),
		_root(root)
	{
	}
	Ref operator*()
	{
		return _node->_kv;
	}
	Ptr operator->()
	{
		return &_node->_kv;
	}
	bool operator!=(const Self& it) const
	{
		return _node != it._node;
	}
	bool operator==(const Self& it) const
	{
		return _node == it._node;
	}
	// 前置++
	Self& operator++()
	{
		if (_node->_right)
		{
			Node* cur = _node->_right;
			while (cur->_left)
			{
				cur = cur->_left;
			}
			_node = cur;
		}
		else
		{
			Node* cur = _node;
			Node* parent = _node->_parent;
			while (parent && parent->_right == cur)
			{
				cur = parent;
				parent = parent->_parent;
			}
			_node = parent;
		}
		return *this;
	}
	// 前置--
	Self& operator--()
	{
		if (_node == nullptr)
		{
			Node* cur = _root;
			while (cur && cur->_right)
			{
				cur = cur->_right;
			}
			_node = cur;
		}
		else if (_node->_left)
		{
			Node* cur = _node->_left;
			while (cur->_right)
			{
				cur = cur->_right;
			}
			_node = cur;
		}
		else
		{
			Node* cur = _node;
			Node* parent = _node->_parent;
			while (parent && parent->_left == cur)
			{
				cur = parent;
				parent = parent->_parent;
			}
			_node = parent;
		}
		return *this;
	}
	// 后置++
	Self operator++(int)
	{
		Self tmp = *this;
		++(*this);
		return tmp;
	}
	// 后置--
	Self operator--(int)
	{
		Self tmp = *this;
		--(*this);
		return tmp;
	}
	Node* _node;
	Node* _root;
};

template<class K, class T, class KeyOfT>
class RBTree
{
	KeyOfT kot;
public:
	typedef RBTreeNode<T> Node;
	typedef RBTreeIterator<T, T&, T*> Iterator;
	typedef RBTreeIterator<T, const T&, const T*> ConstIterator;
	typedef RBTree<K, T, KeyOfT> Self;
	RBTree() = default;
	~RBTree()
	{
		Destory(_root);
	}
	RBTree(const Self& rbtree)
	{
		_root = NodeCopy(rbtree._root, nullptr);
	}
	Self& operator=(const Self& rbtree)
	{
		_root = NodeCopy(rbtree._root, nullptr);
		return *this;
	}
	Iterator Begin()
	{
		Node* cur = _root;
		while (cur && cur->_left)
		{
			cur = cur->_left;
		}
		return Iterator(cur, _root);
	}
	Iterator End()
	{
		return Iterator(nullptr, _root);
	}
	ConstIterator Begin() const
	{
		Node* cur = _root;
		while (cur && cur->_left)
		{
			cur = cur->_left;
		}
		return ConstIterator(cur, _root);
	}
	ConstIterator End() const
	{
		return ConstIterator(nullptr, _root);
	}
	// 旋转代码的实现跟AVL树是一样的，只是不需要更新平衡因子
	pair<Iterator, bool> Insert(const T& kv)
	{
		if (_root == nullptr) {
			_root = new Node(kv);
			_root->_col = BLACK;
			return make_pair(Iterator(_root, _root), true);
		}
		Node* cur = _root;
		Node* parent = nullptr;
		while (cur)
		{
			if (kot(kv) > kot(cur->_kv)) {
				parent = cur;
				cur = cur->_right;
			}
			else if (kot(kv) < kot(cur->_kv)) {
				parent = cur;
				cur = cur->_left;
			}
			else {
				return make_pair(Iterator(cur, _root), false);
			}
		}
		cur = new Node(kv);
		Node* newnode = cur;
		// 新增节点，颜色红色
		cur->_col = RED;
		cur->_parent = parent;
		if (kot(kv) > kot(parent->_kv)) {
			parent->_right = cur;
		}
		else {
			parent->_left = cur;
		}
		while (parent && parent->_col == RED)
		{
			Node* grandfather = parent->_parent;
			//   g
			// p   u
			if (grandfather->_left == parent) {
				Node* uncle = grandfather->_right;
				if (uncle && uncle->_col == RED) {
					// 叔叔存在且为红，变色再继续往上处理
					parent->_col = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else {
					// 叔叔不存在或存在且为黑，旋转+变色
					if (parent->_left == cur) {
						//    g
						//  p   u
						//c
						//单旋
						RotateR(grandfather);
						grandfather->_col = RED;
						parent->_col = BLACK;
					}
					else {
						//    g
						//  p   u
						//    c
						//双旋
						RotateL(parent);
						RotateR(grandfather);
						grandfather->_col = RED;
						cur->_col = BLACK;
					}
					break;
				}
			}
			else {
				Node* uncle = grandfather->_left;
				if (uncle && uncle->_col == RED) {
					// 叔叔存在且为红，变色再继续往上处理
					parent->_col = BLACK;
					uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else {
					// 叔叔不存在或存在且为黑，旋转+变色
					if (parent->_right == cur) {
						//   g
						// u   p
						//       c
						// 单旋
						RotateL(grandfather);
						grandfather->_col = RED;
						parent->_col = BLACK;
					}
					else {
						//   g
						// u   p
						//   c
						// 双旋
						RotateR(parent);
						RotateL(grandfather);
						grandfather->_col = RED;
						cur->_col = BLACK;
					}
					break;
				}
			}
		}
		_root->_col = BLACK;
		return make_pair(Iterator(newnode, _root), true);
	}
	// 删除
	bool Erase(const K& key)
	{
		if (_root == nullptr) return false;
		/*Node* cur = _root;
		Node* parent = nullptr;
		while (cur)
		{
			if (key > kot(cur->_kv)) {
				parent = cur;
				cur = cur->_right;
			}
			else if (key < kot(cur->_kv)) {
				parent = cur;
				cur = cur->_left;
			}
			else {
				break;
			}
		}
		if (cur == nullptr) return false;*/

		Node* cur = Find(key)._node;
		if (cur == nullptr) {
			return false;
		}
		Node* parent = cur->_parent;
		if (cur->_left && cur->_right)
		{
			Node* minRight = cur->_right;
			Node* minRightParent = cur;
			while (minRight->_left)
			{
				minRightParent = minRight;
				minRight = minRight->_left;
			}
			// cur->_kv = minRight->_kv;
			// 用新节点代替cur，解决不能直接代替值的问题
			Node* ReplaceNode = new Node(minRight->_kv);
			ReplaceNode->_col = cur->_col;
			ReplaceNode->_left = cur->_left;
			ReplaceNode->_right = cur->_right;
			ReplaceNode->_parent = cur->_parent;
			if (ReplaceNode->_left) ReplaceNode->_left->_parent = ReplaceNode;
			if (ReplaceNode->_right) ReplaceNode->_right->_parent = ReplaceNode;
			if (cur->_parent) {
				if (cur->_parent->_left == cur) {
					cur->_parent->_left = ReplaceNode;
				}
				else {
					cur->_parent->_right = ReplaceNode;
				}
			}
			else {
				_root = ReplaceNode;
			}
			if (minRightParent == cur)
			{
				// 细节：如果minRightParent指向cur，需要将minRightParent指向ReplaceNode
				minRightParent = ReplaceNode;
			}
			// 删除原节点
			delete cur;
			cur = minRight;
			parent = minRightParent;
		}
		Node* child = nullptr;
		if (cur->_left) child = cur->_left;
		else child = cur->_right;

		if (child) child->_parent = parent;
		if (parent == nullptr) {
			_root = child;
			if (_root) _root->_col = BLACK;
			delete cur;
			return true;
		}
		if (child) {
			if (parent->_left == cur) {
				parent->_left = child;
			}
			else {
				parent->_right = child;
			}
			child->_col = BLACK;
		}
		else {
			Node* pNode = cur;
			if (pNode->_col == RED) {
				if (parent->_left == cur) {
					parent->_left = nullptr;
				}
				else {
					parent->_right = nullptr;
				}
				delete cur;
				return true;
			}
			// pNode表示双黑节点
			while (pNode)
			{
				if (pNode->_col == RED || pNode == _root)
				{
					pNode->_col = BLACK;
					break;
				}
				Node* bro = nullptr;
				if (parent->_left == pNode)
				{
					bro = parent->_right;
					if (bro->_col == BLACK)
					{
						Node* broR = bro->_right;
						Node* broL = bro->_left;
						if (broR && broR->_col == RED)
						{
							broR->_col = bro->_col;
							bro->_col = parent->_col;
							parent->_col = BLACK;
							RotateL(parent);
							break;
						}
						else if (broL && broL->_col == RED)
						{
							broL->_col = parent->_col;
							parent->_col = BLACK;
							RotateR(bro);
							RotateL(parent);
							break;
						}
						else
						{
							bro->_col = RED;
							pNode = parent;
							parent = parent->_parent;
						}
					}
					else
					{
						bro->_col = BLACK;
						parent->_col = RED;
						RotateL(parent);
					}
				}
				else
				{
					bro = parent->_left;
					if (bro->_col == BLACK)
					{
						Node* broR = bro->_right;
						Node* broL = bro->_left;
						if (broL && broL->_col == RED)
						{
							broL->_col = bro->_col;
							bro->_col = parent->_col;
							parent->_col = BLACK;
							RotateR(parent);
							break;
						}
						else if (broR && broR->_col == RED)
						{
							broR->_col = parent->_col;
							parent->_col = BLACK;
							RotateL(bro);
							RotateR(parent);
							break;
						}
						else
						{
							bro->_col = RED;
							pNode = parent;
							parent = parent->_parent;
						}
					}
					else
					{
						bro->_col = BLACK;
						parent->_col = RED;
						RotateR(parent);
					}
				}
			}
			parent = cur->_parent;
			if (parent->_left == cur) {
				parent->_left = nullptr;
			}
			else {
				parent->_right = nullptr;
			}
			delete cur;
		}
		_root->_col = BLACK;
		return true;
	}
	// 查找
	Iterator Find(const K& key)
	{
		Node* cur = _root;
		while (cur)
		{
			if (key > kot(cur->_kv)) {
				cur = cur->_right;
			}
			else if (key < kot(cur->_kv)) {
				cur = cur->_left;
			}
			else {
				return Iterator(cur, _root);
			}
		}
		return Iterator(nullptr, _root);
	}
	// 验证是否平衡
	bool IsBalance()
	{
		if (_root == nullptr) {
			return true;
		}
		if (_root->_col == RED) {
			return false;
		}
		// 参考值
		int refNum = 0;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_col == BLACK) {
				refNum++;
			}
			cur = cur->_left;
		}
		return Check(_root, 0, refNum);
	}
	void InOrder()
	{
		_InOrder(_root);
	}
	int Height()
	{
		return _Height(_root);
	}
	int Size()
	{
		return _Size(_root);
	}
protected:
	// 右单旋
	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;

		subL->_right = parent;
		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;
		Node* parentParent = parent->_parent;
		parent->_parent = subL;
		if (parentParent == nullptr) {
			// 如果parent为根节点则更新根节点
			_root = subL;
			subL->_parent = nullptr;
		}
		else {
			// subL和parentParent建立联系
			if (parentParent->_left == parent) {
				parentParent->_left = subL;
			}
			else {
				parentParent->_right = subL;
			}
			subL->_parent = parentParent;
		}
	}

	//左单旋
	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;

		subR->_left = parent;
		parent->_right = subRL;
		if (subRL)
			subRL->_parent = parent;
		Node* parentParent = parent->_parent;
		parent->_parent = subR;
		if (parentParent == nullptr) {
			// 如果parent为根节点则更新根节点
			_root = subR;
			subR->_parent = nullptr;
		}
		else {
			// subR和parentParent建立联系
			if (parentParent->_left == parent) {
				parentParent->_left = subR;
			}
			else {
				parentParent->_right = subR;
			}
			subR->_parent = parentParent;
		}
	}

	//检查
	bool Check(Node* root, int blackNum, const int& refNum)
	{
		if (root == nullptr) {
			if (blackNum != refNum) {
				cout << "存在黑色结点的数量不相等的路径" << endl;
				return false;
			}
			return true;
		}
		// 检查孩子不太方便，因为孩子有两个，且不一定存在，反过来检查父亲就方便多了
		if (root->_col == RED && root->_parent && root->_parent->_col == RED)
		{
			cout << root->_kv.first << "存在连续的红色节点" << endl;
			return false;
		}
		if (root->_col == BLACK)
		{
			blackNum++;
		}
		return Check(root->_left, blackNum, refNum) && Check(root->_right, blackNum, refNum);
	}

	int _Size(Node* root)
	{
		if (root == nullptr) return 0;
		return _Size(root->_left) + _Size(root->_right) + 1;
	}

	int _Height(Node* root)
	{
		if (root == nullptr)
			return 0;
		int leftHeight = _Height(root->_left);
		int rigthHeight = _Height(root->_right);
		return max(leftHeight, rigthHeight) + 1;
	}

	void _InOrder(Node* root)
	{
		if (root == nullptr) return;
		_InOrder(root->_left);
		cout << root->_kv.first << ":" << root->_kv.second << endl;
		_InOrder(root->_right);
	}

	void Destory(Node* root)
	{
		if (root == nullptr) return;
		if (root->_left) Destory(root->_left);
		if (root->_right) Destory(root->_right);
		delete root;
		root = nullptr;
	}

	Node* NodeCopy(Node* root, Node* parent)
	{
		if (root == nullptr) return nullptr;
		Node* newnode = new Node(root->_kv);
		newnode->_col = root->_col;
		newnode->_parent = parent;
		newnode->_left = NodeCopy(root->_left, newnode);
		newnode->_right = NodeCopy(root->_right, newnode);
		return newnode;
	}
private:
	Node* _root = nullptr;
};